using FileManager.Models;
using FileManager.Services;
using FileManager.Views;
using System.Collections.Generic;
using System.Windows.Input;
using System.Windows;
using System.Windows.Threading;
using System.Linq;
using static FileManager.Services.FileScanner;
using System;

namespace FileManager.ViewModels
{
    public class MainViewModel : BaseViewModel
    {
        public FileScanner FileScanner { get; set; }
        public FileManagerService FileManagerService { get; set; }
        public DuplicateFileFinder DuplicateFileFinder { get; set; }
        public DatFileDecryptor DatFileDecryptor { get; set; }
        public DatabaseBackupService DatabaseBackupService { get; set; }
        public FileExportService FileExportService { get; set; }
        public AppDbContext DbContext { get; set; }
        public AppSettings Settings { get; set; }

        // 文件详情视图模型
        public FileDetailViewModel FileDetailViewModel { get; set; }

        // 命令
        public ICommand ScanFilesCommand { get; }
        public ICommand FindDuplicateFilesCommand { get; }
        public ICommand ExportSelectedFilesCommand { get; }
        public ICommand OpenSettingsCommand { get; }
        public ICommand ShowFilesByTypeCommand { get; }
        public ICommand ShowImportantFilesCommand { get; }
        public ICommand CleanupInvalidIndexesCommand { get; }
        public ICommand SearchFilesCommand { get; }

        // 属性
        private List<FileItem> _files = new List<FileItem>();
        public List<FileItem> Files
        {
            get => _files;
            set => SetProperty(ref _files, value);
        }

        private FileItem _selectedFile;
        public FileItem SelectedFile
        {
            get => _selectedFile;
            set
            {
                if (SetProperty(ref _selectedFile, value))
                {
                    // 当选择文件改变时，同步到FileDetailViewModel
                    if (FileDetailViewModel != null)
                    {
                        FileDetailViewModel.SelectedFile = value;
                    }
                }
            }
        }

        private string _searchKeyword;
        public string SearchKeyword
        {
            get => _searchKeyword;
            set => SetProperty(ref _searchKeyword, value);
        }

        private List<ChatObject> _chatObjects = new List<ChatObject>();
        public List<ChatObject> ChatObjects
        {
            get => _chatObjects;
            set => SetProperty(ref _chatObjects, value);
        }

        private ChatObject _selectedChatObject;
        public ChatObject SelectedChatObject
        {
            get => _selectedChatObject;
            set => SetProperty(ref _selectedChatObject, value);
        }

        private List<Tag> _tags = new List<Tag>();
        public List<Tag> Tags
        {
            get => _tags;
            set => SetProperty(ref _tags, value);
        }

        private Tag _selectedTag;
        public Tag SelectedTag
        {
            get => _selectedTag;
            set => SetProperty(ref _selectedTag, value);
        }

        // 状态属性
        private string _statusMessage = "就绪";
        public string StatusMessage
        {
            get => _statusMessage;
            set => SetProperty(ref _statusMessage, value);
        }

        private bool _isScanning = false;
        public bool IsScanning
        {
            get => _isScanning;
            set => SetProperty(ref _isScanning, value);
        }

        private double _scanProgress = 0;
        public double ScanProgress
        {
            get => _scanProgress;
            set => SetProperty(ref _scanProgress, value);
        }

        public MainViewModel()
        {
            // 初始化命令（服务将在外部设置）
            ScanFilesCommand = new RelayCommand(_ => ScanFiles());
            FindDuplicateFilesCommand = new RelayCommand(_ => FindDuplicateFiles());
            ExportSelectedFilesCommand = new RelayCommand(_ => ExportSelectedFiles());
            OpenSettingsCommand = new RelayCommand(_ => OpenSettings());
            ShowFilesByTypeCommand = new RelayCommand(param => ShowFilesByType(param as string));
            ShowImportantFilesCommand = new RelayCommand(_ => ShowImportantFiles());
            CleanupInvalidIndexesCommand = new RelayCommand(_ => CleanupInvalidIndexes());
            SearchFilesCommand = new RelayCommand(_ => SearchFiles());

            // 初始化FileDetailViewModel
            FileDetailViewModel = new FileDetailViewModel();

            // 延迟加载初始数据，等待服务实例设置完成
        }

        /// <summary>
        /// 加载初始数据
        /// </summary>
        public void Initialize()
        {
            if (FileManagerService == null)
            {
                // 如果服务未设置，则创建默认实例
                DbContext = new AppDbContext();
                FileScanner = new FileScanner(DbContext);
                FileManagerService = new FileManagerService(DbContext);
                DuplicateFileFinder = new DuplicateFileFinder(DbContext);
                DatFileDecryptor = new DatFileDecryptor();
                DatabaseBackupService = new DatabaseBackupService();
                FileExportService = new FileExportService(DatFileDecryptor);
                Settings = new AppSettings();
            }

            // 加载初始数据
            LoadInitialData();
        }

        private async void LoadInitialData()
        {
            // 加载初始数据
            try
            {
                StatusMessage = "正在加载数据...";

                // 加载文件列表
                var files = await FileManagerService.GetAllFilesAsync();
                Files = new List<FileItem>(files);

                // 加载聊天对象
                var chatObjects = await FileManagerService.GetAllChatObjectsAsync();
                ChatObjects = new List<ChatObject>(chatObjects);

                // 加载标签
                var tags = await FileManagerService.GetAllTagsAsync();
                Tags = new List<Tag>(tags);

                StatusMessage = $"已加载 {Files.Count} 个文件";
            }
            catch (Exception ex)
            {
                StatusMessage = "加载数据失败";
                MessageBox.Show($"加载初始数据时出错: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private async void ScanFiles()
        {
            // 扫描文件逻辑
            try
            {
                // 从Settings中获取扫描目录
                if (Settings.ScanDirectories == null || !Settings.ScanDirectories.Any())
                {
                    MessageBox.Show("请先在设置中添加扫描目录", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                    return;
                }

                IsScanning = true;
                StatusMessage = "准备扫描文件...";
                ScanProgress = 0;

                // 订阅扫描进度事件
                FileScanner.ProgressChanged += OnScanProgressChanged;
                FileScanner.ScanCompleted += OnScanCompleted;

                // 开始扫描
                await FileScanner.StartScanAsync(Settings.ScanDirectories);
            }
            catch (Exception ex)
            {
                IsScanning = false;
                StatusMessage = "扫描失败";
                MessageBox.Show($"扫描文件时出错: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void OnScanProgressChanged(object sender, ScanProgressEventArgs e)
        {
            // 更新UI主线程上的进度
            Application.Current.Dispatcher.Invoke(() =>
            {
                ScanProgress = e.ProgressPercentage;
                StatusMessage = $"正在扫描: {e.CurrentFile} ({e.ProcessedFiles}/{e.TotalFiles})";
            });
        }

        private void OnScanCompleted(object sender, ScanCompletedEventArgs e)
        {
            // 更新UI主线程上的状态
            Application.Current.Dispatcher.Invoke(() =>
            {
                IsScanning = false;
                ScanProgress = 0;
                StatusMessage = e.Cancelled ? "扫描已取消" : "扫描完成";

                // 显示扫描结果
                MessageBox.Show(e.Message, "扫描完成", MessageBoxButton.OK, MessageBoxImage.Information);

                // 重新加载文件列表
                LoadInitialData();

                // 取消订阅事件
                FileScanner.ProgressChanged -= OnScanProgressChanged;
                FileScanner.ScanCompleted -= OnScanCompleted;
            });
        }

        private void FindDuplicateFiles()
        {
            // 查找重复文件逻辑
            var window = new DuplicateFilesWindow(this);
            window.ShowDialog();
        }

        private void ExportSelectedFiles()
        {
            // 导出文件逻辑
            // 实际应用中，这里应该获取用户选择的文件
            // 这里简化处理，假设导出所有文件
            var filesToExport = Files;
            var exportViewModel = new ExportFilesViewModel(FileExportService, filesToExport);
            var window = new ExportFilesWindow(exportViewModel);
            window.ShowDialog();
        }

        private void OpenSettings()
        {
            // 打开设置窗口逻辑
            var settingsViewModel = new SettingsViewModel(Settings, DatabaseBackupService, FileManagerService);
            var window = new SettingsWindow(settingsViewModel);
            window.ShowDialog();

            // 设置窗口关闭后重新加载数据
            LoadInitialData();
        }

        private async void ShowFilesByType(string fileType)
        {
            // 按文件类型显示文件逻辑
            try
            {
                StatusMessage = $"正在加载{fileType}文件...";
                var files = await FileManagerService.GetFilesByTypeAsync(fileType);
                Files = new List<FileItem>(files);
                StatusMessage = $"已加载 {files.Count} 个{fileType}文件";
            }
            catch (Exception ex)
            {
                StatusMessage = "加载文件失败";
                MessageBox.Show($"加载{fileType}文件时出错: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private async void ShowImportantFiles()
        {
            // 显示重要文件逻辑
            try
            {
                StatusMessage = "正在加载重要文件...";
                var files = await FileManagerService.GetImportantFilesAsync();
                Files = new List<FileItem>(files);
                StatusMessage = $"已加载 {files.Count} 个重要文件";
            }
            catch (Exception ex)
            {
                StatusMessage = "加载文件失败";
                MessageBox.Show($"加载重要文件时出错: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private async void CleanupInvalidIndexes()
        {
            // 清理无效索引逻辑
            try
            {
                StatusMessage = "正在清理无效索引...";
                await FileManagerService.CleanupInvalidIndexesAsync();
                // 重新加载文件列表
                LoadInitialData();
            }
            catch (Exception ex)
            {
                StatusMessage = "清理失败";
                MessageBox.Show($"清理无效索引时出错: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private async void SearchFiles()
        {
            // 搜索文件逻辑
            if (string.IsNullOrEmpty(SearchKeyword))
            {
                MessageBox.Show("请输入搜索关键词", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                return;
            }

            try
            {
                StatusMessage = $"正在搜索: {SearchKeyword}...";
                var files = await FileManagerService.SearchFilesAsync(SearchKeyword);
                Files = new List<FileItem>(files);
                StatusMessage = $"找到 {files.Count} 个匹配的文件";
            }
            catch (Exception ex)
            {
                StatusMessage = "搜索失败";
                MessageBox.Show($"搜索文件时出错: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
    }
}